import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
import { login } from '@/store/actions'
import logo from '../../assets/logo.png'
import './index.scss'

const Login = (props) => {
  console.log('login', props)
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = async (values) => {
    const { mobile, code } = values
    try {
      await dispatch(login(mobile, code))
      history.replace(props.location.state?.from || '/')
    } catch (e) {
      console.dir(e)
      message.error(e.response?.data?.message || '登录失败')
    }
  }
  // 函数校验
  /**
   *
   * @param {*} field 表单域信息
   * @param {*} value 表单项值
   * @returns
   */
  const validAgree = (field, value) => {
    // console.log(field, value)
    if (!value) {
      return Promise.reject(new Error('勾选同意「用户协议」和「隐私条款」！'))
    }
    return Promise.resolve()
  }

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            remember: true,
          }}
          validateTrigger={['onBlur', 'onChange']}>
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
              { required: true, message: '请输入手机号' },
            ]}>
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码6个字符' },
              { required: true, message: '请输入验证码' },
            ]}>
            <Input.Password size="large" placeholder="请输入密码" />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            rules={[
              {
                validator: validAgree,
                // validateTrigger: 'onBlur',
              },
            ]}>
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
